#include "messagetextedit.h"

#include <QMessageBox>

MessageTextEdit::MessageTextEdit(QWidget *parent) : QTextEdit(parent)
{
    this->setMaximumHeight(60);
}

MessageTextEdit::~MessageTextEdit()
{

}

QVector<MsgInfo> MessageTextEdit::getMsgList()
{
    m_get_msg_list.clear();

    QString doc = this->document()->toPlainText();
    QString text = "";
    int index_url = 0;
    int count = m_msg_list.size();

    for (int index = 0; index < doc.size(); ++ index) {
        // 处理富文本
        if (doc[index] == QChar::ObjectReplacementCharacter) {
            if (!text.isEmpty()) {
                QPixmap pix;
                insertMsgList(m_get_msg_list, "text", text, pix);
                text.clear();
            }

            while(index_url < count)
            {
                MsgInfo msg = m_msg_list[index_url];
                if (this->document()->toHtml().contains(msg.content, Qt::CaseSensitive))
                {
                    index_url++;
                    m_get_msg_list.append(msg);
                    break;
                }
                index_url++;
            }
        } else {
            // 普通文本
            text.append(doc[index]);
        }
    }

    if (!text.isEmpty()) {
        QPixmap pix;
        insertMsgList(m_get_msg_list, "text", text, pix);
        text.clear();
    }

    m_msg_list.clear();
    this->clear();

    return m_get_msg_list;
}

void MessageTextEdit::insertFileFromUrl(const QStringList &urls)
{
    if (urls.isEmpty()) {
        return ;
    }

    foreach (QString url, urls) {
        if (isImage(url)) {
            insertImages(url);
        } else {
            insertTextFile(url);
        }
    }
}

void MessageTextEdit::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->source() == this) {
        event->ignore();
    } else {
        event->accept();
    }
}

void MessageTextEdit::dropEvent(QDropEvent *event)
{
    insertFromMimeData(event->mimeData());
    event->accept();
}

void MessageTextEdit::keyPressEvent(QKeyEvent *e)
{
    if ( (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) && !(e->modifiers() & Qt::ShiftModifier) )
    {
        emit send();
        return;
    }

    QTextEdit::keyPressEvent(e);
}

bool MessageTextEdit::isImage(QString url)
{
    QString imageFormat = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp";
    QStringList imageFormatList = imageFormat.split(",");
    QFileInfo fileInfo(url);
    // 获取文件的后缀
    QString suffix = fileInfo.suffix();
    if ( imageFormatList.contains(suffix, Qt::CaseInsensitive) ){
        return true;
    }

    return false;
}

void MessageTextEdit::insertMsgList(QVector<MsgInfo> &list, QString flag, QString text, QPixmap pix)
{
    MsgInfo msg;
    msg.msgFlag = flag;
    msg.content = text;
    msg.pixmap = pix;
    list.append(msg);
}

void MessageTextEdit::insertImages(const QString &url)
{
    QImage image(url);
    // 按比例缩放图片
    if (image.width() > 120 || image.height() >  80) {
        if (image.width() > image.height()) {
            image = image.scaledToWidth(120, Qt::SmoothTransformation);
        } else {
            image = image.scaledToHeight(80, Qt::SmoothTransformation);
        }
    }
    QTextCursor cursor = this->textCursor();
    // 插入图片
    cursor.insertImage(image, url);

    insertMsgList(m_msg_list, "image", url, QPixmap::fromImage(image));
}

void MessageTextEdit::insertTextFile(const QString &url)
{
    QFileInfo fileinfo(url);
    if (fileinfo.isDir()) {
        QMessageBox::information(this, "提示", "只允许拖拽单个文件!");
        return ;
    }

    if (fileinfo.size() > 100 * 1024 * 1024)
    {
        QMessageBox::information(this, "提示", "发送的文件大小不能大于100M");
        return;
    }

    QPixmap pix = getFileIconPixmap(url);
    QTextCursor cursor = this->textCursor();
    cursor.insertImage(pix.toImage(), url);
    insertMsgList(m_msg_list, "file", url, pix);
}

void MessageTextEdit::insertFromMimeData(const QMimeData *source)
{
    QStringList urls = getUrl(source->text());

    if (urls.isEmpty()) {
        return ;
    }

    foreach (QString url, urls)
    {
        if (isImage(url)) {
            insertImages(url);
        } else {
            insertTextFile(url);
        }
    }
}

bool MessageTextEdit::canInsertFromMimeData(const QMimeData *source) const
{
    return QTextEdit::canInsertFromMimeData(source);
}

QStringList MessageTextEdit::getUrl(QString text)
{
    QStringList urls;
    if (text.isEmpty()) {
        return urls;
    }

    QStringList list = text.split("\n");
    foreach (QString url, list) {
        if (!url.isEmpty()) {
            QStringList str = url.split("///");
            if (str.size() >= 2) {
                urls.append(str.at(1));
            }
        }
    }

    return urls;
}

QPixmap MessageTextEdit::getFileIconPixmap(const QString &url)
{
    // 获取文件图标
    QFileIconProvider provder;
    QFileInfo fileinfo(url);
    QIcon icon = provder.icon(fileinfo);

    // 获取文件大小
    QString strFileSize = getFileSize(fileinfo.size());

    QFont font(QString("宋体"), 10, QFont::Normal, false);
    QFontMetrics fontMetrics(font);
    QSize textSize = fontMetrics.size(Qt::TextSingleLine, fileinfo.fileName());

    QSize fileSize = fontMetrics.size(Qt::TextSingleLine, strFileSize);
    int maxWidth = textSize.width() > fileSize.width() ? textSize.width() : fileSize.width();
    QPixmap pix(maxWidth + 50 + 10, 50);
    pix.fill();

    QPainter painter;
    painter.begin(&pix);

    // 绘制文件图标
    QRect rect(0, 0, 50, 50);
    painter.drawPixmap(rect, icon.pixmap(40, 40));
    painter.setPen(Qt::black);
    // 显示文件名
    QRect rectText(50 + 10, 3, textSize.width(), textSize.height());
    painter.drawText(rectText, fileinfo.fileName());
    // 显示文件大小
    QRect rectFile(50 + 10, textSize.height() + 5, fileSize.width(), fileSize.height());
    painter.drawText(rectFile, strFileSize);

    painter.end();

    return pix;
}

QString MessageTextEdit::getFileSize(qint64 size)
{
    QString Unit;
    double num;
    if(size < 1024){
        num = size;
        Unit = "B";
    }
    else if(size < 1024 * 1224){
        num = size / 1024.0;
        Unit = "KB";
    }
    else if(size <  1024 * 1024 * 1024){
        num = size / 1024.0 / 1024.0;
        Unit = "MB";
    }
    else{
        num = size / 1024.0 / 1024.0/ 1024.0;
        Unit = "GB";
    }
    return QString::number(num,'f',2) + " " + Unit;
}

void MessageTextEdit::textEditChanged()
{

}
